package cn.com.winning.ecare.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.activity.GhFrive.MyAdapter;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.JsonBuilder;
import cn.com.winning.ecare.utils.StringUtil;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UtilPay;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**
 * 我的预约显示界面
 * 
 * @author Administrator
 */
public class GhSeven extends Activity
{
	private ImageButton ks_preview = null;
	private CustomProgressDialog proDialog;// 加载框
	private GhSeven oThis = this;
	private List<Map<String, Object>> list_yy = new ArrayList<Map<String, Object>>();;
	private Intent mIntent;
	private String strysgh;
	private String strpbdate;
	MyApplication myApp;
	private TextView hzxm, sfzh, sjh, mzsj, ghks, ysxm, ghfy, czrq, mzdd, yytitle;
	String yzm;
	private int preID = -1;
	private MyAdapter myAdapter = null;
	private ListView lv = null;
	private Button reset_button;
	private String nowdate;
	private ImageButton mainselected;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.gh_seven);
		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
		// 获取控件
		findView();

		// 获取数据
		getData();

		// 点击事件
		setOnClick();
	}

	private void setOnClick()
	{
		// 设置preview监听
		ks_preview.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub

				finish();

			}
		});
		mainselected.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(oThis, Mainmean.class);
				startActivity(intent);
				oThis.finish();
			}
		});

	}

	private void findView()
	{
		lv = (ListView) this.findViewById(R.id.yyxx_list);
		setData();
		ks_preview = (ImageButton) this.findViewById(R.id.yy_preview);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		nowdate = df.format(new Date());
		mainselected = (ImageButton) this.findViewById(R.id.mainselected);
	}

	private void getData()
	{
		proDialog = CustomProgressDialog.createDialog(this);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();
	}

	class LoadData implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			iniYYxx();
			Looper.loop();
		}
	}

	private void iniYYxx()
	{
		try
		{
			mIntent = getIntent();
			String ghdh = "";
			String strpbdate = "";
			if (mIntent != null)
			{
				ghdh = mIntent.getStringExtra("ghdh");
				strpbdate = mIntent.getStringExtra("strpbdate");
			}
			Message msg = myHandler.obtainMessage();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("userid", myApp.getAccount()));
			ls.add(new BasicNameValuePair("memberid", myApp.getMemberid()));// 家庭成员id
			ls.add(new BasicNameValuePair("ghdh", ghdh));
			ls.add(new BasicNameValuePair("strpbdate", strpbdate));

			ls.add(new BasicNameValuePair("hzxm", myApp.getHzxm()));
			ls.add(new BasicNameValuePair("sfzh", myApp.getSfzh()));
			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.GETGHXXLIST, ls);
			List<Map<String, Object>> tempmain = new ArrayList<Map<String, Object>>();
			if (json != null && !json.equals(""))
			{
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (json.getString("qxinfo").equals("FAILURE"))
					{
						Toast.makeText(GhSeven.this, "您好，您的预约单取消失败！", Toast.LENGTH_SHORT).show();
					}
					else if (json.getString("qxinfo").equals("SUCCESS"))
					{
						Toast.makeText(GhSeven.this, "您好，您的预约单已被取消！", Toast.LENGTH_SHORT).show();
					}
					else if (json.getString("qxinfo").indexOf("@") != -1)
					{
						Toast.makeText(GhSeven.this, json.getString("qxinfo").split("@")[0], Toast.LENGTH_SHORT).show();
					}
					if (new JSONArray(json.getString("yyinfolist")).length() > 0)
					{

						// 获取yy信息
						JSONArray jsonArr = new JSONArray(json.getString("yyinfolist"));
						JSONObject js = null;
						// list_yy = new ArrayList<Map<String, Object>>();
						for (int i = 0; i < jsonArr.length(); i++)
						{
							Map<String, Object> map_yy = new HashMap<String, Object>();
							js = jsonArr.getJSONObject(i);
							map_yy.put("ghdh", js.getString("ghdh"));
							map_yy.put("yymc", js.getString("yymc"));
							map_yy.put("ksmc", js.getString("ksmc"));
							map_yy.put("ysxm", js.getString("ysxm"));
							map_yy.put("yyrq", js.getString("yyrq"));
							map_yy.put("czrq", js.getString("czrq"));
							map_yy.put("ghf", js.getString("ghf"));
							map_yy.put("payflag", js.getString("payflag"));
							if (js.has("yzm"))
							{
								map_yy.put("yzm", js.getString("yzm"));
								yzm = js.getString("yzm");
							}
							else
							{
								yzm = "";
							}
							if (js.has("cardno"))
							{
								map_yy.put("cardno", js.getString("cardno"));
							}
							else
							{
								map_yy.put("cardno", "");
							}
							tempmain.add(map_yy);
						}
						msg.what = 0;
						msg.obj = tempmain;

					}
					else
					{
						msg.what = -1;
						msg.obj = "暂无数据";
					}

				}
				else
				{
					msg.what = -1;
					msg.obj = "系统错误";
				}

			}
			else
			{
				msg.what = -1;
				msg.obj = "网络连接失败!";
			}
			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 捕捉异常
			Message msg = myHandler.obtainMessage();
			msg.what = -1;
			msg.obj = e.toString();
			myHandler.sendMessage(msg);
		}
	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case -1:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					// oThis.finish();
					break;
				case 0:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					if (msg.obj != null)
					{
						list_yy = (List<Map<String, Object>>) msg.obj;
						JsonBuilder.getInstance().toJson(msg.obj);
					}
					// if (myAdapter == null)
					// {
					// myAdapter = new MyAdapter(oThis);
					// }
					// lv.setAdapter(myAdapter);
					myAdapter.notifyDataSetChanged();
					break;
				case 1:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					// setHosInfo();
					break;

				default:
					break;
			}
		};
	};

	private void setData()
	{
		myAdapter = new MyAdapter();
		lv.setAdapter(myAdapter);
	}

	class MyAdapter extends BaseAdapter
	{

		@Override
		public int getCount()
		{
			// TODO Auto-generated method stub
			return list_yy.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return list_yy.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null)
			{
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.gh_seven_item, null);
				holder = new ViewHolder();
				holder.tv_mzsj = (TextView) convertView.findViewById(R.id.mzsj);
				holder.tv_ghks = (TextView) convertView.findViewById(R.id.ghks);
				holder.tv_ysxm = (TextView) convertView.findViewById(R.id.ysxm);
				holder.tv_ghfy = (TextView) convertView.findViewById(R.id.ghfy);
				holder.tv_mzdd = (TextView) convertView.findViewById(R.id.mzdd);
				holder.tv_card = (TextView) convertView.findViewById(R.id.card);
				holder.gh_seven_item_bt = (RelativeLayout) convertView.findViewById(R.id.gh_seven_item_bt);
				holder.zxff = (Button) convertView.findViewById(R.id.zxff);// 在线支付
				holder.tv_yzm = (TextView) convertView.findViewById(R.id.yzm);
				// holder.gh_seven_item_ll=(LinearLayout)
				// convertView.findViewById(R.id.gh_seven_item_ll);

				convertView.setTag(holder);

			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			holder.tv_mzsj.setText("门诊时间:" + list_yy.get(position).get("yyrq"));
			holder.tv_ghks.setText("挂号科室:" + list_yy.get(position).get("ksmc"));
			holder.tv_ysxm.setText("医生姓名:" + list_yy.get(position).get("ysxm"));
			holder.tv_ghfy.setText(list_yy.get(position).get("ghf").toString());
			if (StringUtil.isEquals("hb_qhd_01", myApp.getYydm()))
			{
				holder.tv_mzdd.setText("换号地点:有就诊卡卡号的患者请拿此卡号就诊卡到医院自助机或者相应科室护士分诊台取预约号序就诊。没有就诊卡的患者请到办卡结算中心办理就诊卡。");
			}
			else
			{
				holder.tv_mzdd.setText("换号地点:门诊预约服务中心");
			}
			if (StringUtil.isEmpty(list_yy.get(position).get("cardno").toString()))
			{
				holder.tv_card.setVisibility(View.GONE);
			}
			else
			{
				holder.tv_card.setText("就诊卡号:" + list_yy.get(position).get("cardno"));
				holder.tv_card.setVisibility(View.VISIBLE);
			}
			String yyrq = list_yy.get(position).get("yyrq").toString().substring(0, 10);
			int result = nowdate.compareTo(yyrq);

			reset_button = (Button) convertView.findViewById(R.id.reset_button);
			yytitle = (TextView) convertView.findViewById(R.id.yytitle);
			final String ghdh = list_yy.get(position).get("ghdh").toString();
			final String sjd = list_yy.get(position).get("yyrq").toString();
			final String ghfy = list_yy.get(position).get("ghf").toString();
			String aa = list_yy.get(position).get("payflag").toString();
			if (result > 0)
			{
				reset_button.setVisibility(View.GONE);
				// holder.gh_seven_item_ll.setVisibility(View.GONE);
				holder.tv_yzm.setVisibility(View.GONE);
				yytitle.setText("失效预约");
				holder.gh_seven_item_bt.setBackgroundColor(Color.parseColor("#818181"));

			}
			else
			{
				yytitle.setText("有效预约");
				// holder.gh_seven_item_ll.setVisibility(View.VISIBLE);
				if (yzm.equals(""))
				{
					holder.tv_yzm.setVisibility(View.GONE);
					// holder.tv_yzm.setText("");

				}
				else
				{
					holder.tv_yzm.setVisibility(View.VISIBLE);
					holder.tv_yzm.setText("验证码:" + list_yy.get(position).get("yzm").toString());
				}
				holder.gh_seven_item_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.title_bar));

				if (aa.equals("1"))
				{// 已经付费不能退号
					reset_button.setVisibility(View.GONE);
				}
				else
				{
					reset_button.setVisibility(View.VISIBLE);
				}

				reset_button.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						// TODO Auto-generated method stub
						finish();
						Intent intent = new Intent(GhSeven.this, GhSeven.class);
						intent.putExtra("ghdh", ghdh);
						intent.putExtra("strpbdate", sjd);
						startActivity(intent);
					}
				});

			}

			if (myApp.getGhpayflag() != null && myApp.getGhpayflag().equals("1"))
			{
				holder.zxff.setVisibility(View.VISIBLE);

				if (aa.equals("1"))
				{// 已付费
					holder.zxff.setText("已付费");
					holder.zxff.setEnabled(false);
				}
				else
				{
					holder.zxff.setText("在线支付");
					if (result > 0)
					{
						holder.zxff.setEnabled(false);
					}
					else
					{

						holder.zxff.setEnabled(true);
					}

				}

			}
			else
			{
				holder.zxff.setVisibility(View.GONE);
			}

			holder.zxff.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					// TODO Auto-generated method stub
					// 拿到Fiap对象并传入容器
					// Fiap fiap = new Fiap(GhSix.this);
					// // 调用支付方法，并传入支付金额
					// fiap.android_pay(0.01);
					try
					{
						double ghf = Double.parseDouble(ghfy);

						UtilPay pay = new UtilPay();

						if (ghf > 0)
						{
							pay.android_pay(URLUtils.HOST, ghdh, ghf, GhSeven.this, "挂号费用", "挂号费用");
						}
						else
						{
							Toast.makeText(oThis, "支付金额为负数，请检查！", Toast.LENGTH_SHORT).show();
						}

					}
					catch (Exception e)
					{
						Toast.makeText(oThis, "支付金额异常，请检查！", Toast.LENGTH_SHORT).show();

					}

				}
			});

			return convertView;
		}

	}

	public class ViewHolder
	{
		private TextView tv_mzsj;
		private TextView tv_ghks;
		private TextView tv_ysxm;
		private TextView tv_ghfy;
		private TextView tv_mzdd;
		private RelativeLayout gh_seven_item_bt;
		private Button zxff;
		private TextView tv_yzm;
		private TextView tv_card;
		private LinearLayout gh_seven_item_ll;
	}

}
